package generic;

import java.util.Arrays;

//泛型
public class Demo {
    static class Student{
        public String name;
        public int age;

        public Student(String name,int age){
            this.name = name;
            this.age = age;
        }

        @Override
        public String toString(){
            return "学生{" + "name: " + name + " age: " + age + "}";
        }
    }
    //带泛型的比较方法
    public static <T> int compare(T s1,T s2){
        Student a1 = (Student) s1;
        Student a2 = (Student) s2;
        if(a1.age > a2.age){
            return 1;
        }else if(a1.age < a2.age){
            return -1;
        }else{
            return 0;
        }
    }
    //带泛型的交换方法
    public static <T> void swap(T[]array,int i,int j){
        T tmp = array[i];
        array[i] = array[j];
        array[j] = tmp;
    }
    //带泛型的冒泡排序
    public static <T> void bubbleSort(T[] array){
        for(int i = 0;i < array.length - 1;i++){
            for(int j = 0;j < array.length - i - 1;j++){
            //必须写一个比较方法，不能直接进行比较
                T s1 = array[j];
                T s2 = array[j + 1];
                int tmp = compare(s1,s2);
                if(tmp > 0){
                    swap(array,j,j + 1);
                }
            }
        }
    }
    //不带泛型的冒泡排序
    public static void bubbleSort(int[] array){
        for(int i = 0;i < array.length - 1;i++){
            for(int j = 0;j < array.length - i - 1;j++){
                int tmp = 0;
                if(array[j] > array[j + 1]){
                    tmp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = tmp;
                }
            }
        }
    }

    public static void main(String[] args) {
        int[] a1 = {1,6,2,9,4,5};
        bubbleSort(a1);
        System.out.println(Arrays.toString(a1));

        Student[] array = {
                new Student("张三",18),
                new Student("李四",20),
                new Student("王五",17),
                new Student("钱六",8),
        };
        bubbleSort(array);
        System.out.println(Arrays.toString(array));
    }
}
